package com.betterman.service.impl;

import com.betterman.mapper.PostMapper;
import com.betterman.pojo.Post;
import com.betterman.service.PostService;
import com.betterman.utils.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 博客发表实现类
 * @author <a href="mailto:foxfocus@163.com">fox</a>
 * @version 10:06 上午 2020/8/6
 */
@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;
    /**
     * 根据关键字查询分页
     *
     * @param keywords
     * @param page
     * @param pageSize
     */
    @Override
    public PageResult queryPosts(String keywords, Integer page, Integer pageSize) {
        Example example = new Example(Post.class);
        example.orderBy("created").desc();
        // 此处区分中文和英文
        Example.Criteria criteria = example.createCriteria();
        // 重点： 模糊查询需要在查询条件加上 %, 使用 OR 关联
        criteria.orLike("title", "%"+keywords+"%").orLike("content", "%"+keywords+"%");

        PageHelper.startPage(page, pageSize);
        List<Post> posts = postMapper.selectByExample(example);
        // 转换成 page 对象
        PageInfo<Post> pageInfo = new PageInfo<>(posts);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setRows(posts);
        // 总页数
        pageResult.setTotal(pageInfo.getPages());
        // 总记录数
        pageResult.setRecords(pageInfo.getTotal());
        return pageResult;
    }
}
